package com.ddwl.message.service;

import com.ddwl.common.exception.CommonException;
import com.ddwl.common.exception.ExceptionCode;
import com.ddwl.common.util.ObjectUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.message.mapper.FeedbackMapper;
import com.ddwl.message.model.Feedback;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.message.FeedbackBo;
import com.ddwl.schema.bo.message.FeedbackSearchBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.message.FeedbackVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 在线反馈服务
 *
 * @author Fu Zhaohui
 */
@Service
public class FeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Transactional(rollbackFor = Throwable.class)
    public void save(FeedbackBo bo) {
        Feedback entity = new Feedback();
        BeanUtils.copyProperties(bo, entity);
        entity.setId(UUIDGenerator.getShortUUID());
        feedbackMapper.insert(entity);
    }

    public PageVo<FeedbackVo> page(PageBo<FeedbackSearchBo> pageBo) {
        PageVo<FeedbackVo> pageVo = new PageVo<>();
        BeanUtils.copyProperties(pageBo, pageVo);
        pageVo.setSize(pageBo.getPageSize());
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize());
        Page<Feedback> pageable = (Page<Feedback>) feedbackMapper.findAll(pageBo.getParam());
        pageVo.setData(pageable.getResult().stream().map(entity -> {
            FeedbackVo vo = new FeedbackVo();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }).collect(Collectors.toList()));
        return pageVo;
    }

    public void resolve(FeedbackBo bo) {
        Feedback entity = feedbackMapper.findByPk(bo.getId());
        if (entity == null) {
            throw new CommonException(ExceptionCode.DATA_NOT_EXISTS);
        }
        entity.setStatus(bo.getStatus());
        entity.setRemark(bo.getRemark());
        entity.setEmpId(bo.getUserId());
        feedbackMapper.update(entity);
    }
}
